package com.ruoyi.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.framework.web.service.SysLoginService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.service.SysDeptServiceImpl;
import com.ruoyi.service.SysPostServiceImpl;
import com.ruoyi.service.SysRoleServiceImpl;
import com.ruoyi.service.SysUserServiceImpl;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@RestController("系统用户/")
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserServiceImpl userService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysRoleServiceImpl roleService;

    @Autowired
    private SysDeptServiceImpl deptService;

    @Autowired
    private SysPostServiceImpl postService;

    /**
     * 根据用户编号获取详细信息
     */

    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUserServiceImpl.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 登陆接口
     */
    @RequestMapping("/loginByUserId")
    public Object loginByUserId(int userId) {
        return sysLoginService.loginByUserId(userId);
    }

    /**
     * 根据用户编号获取详细信息
     */

    @GetMapping(value = "/userInfo")
    public AjaxResult userInfo() {
        return success(userService.getUserInfo());
    }


    @RequestMapping(value = "/waitAuditList", name = "待审核列表")
    public Object waitAuditList(Page page, @RequestParam Map<String, Object> param) {
        userService.waitAuditList(page, param);
        return page;
    }


    /**
     * 新增用户
     */

    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        Assert.isFalse(!userService.checkPhoneUnique(user), "手机号码已存在");
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */


    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user,false));
    }

    /**
     * 删除用户
     */


    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */


    @RequestMapping(value = "/resetPwd", name = "重置密码")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    @RequestMapping(value = "/updateUse", name = "停用启用")
    @Transactional(rollbackFor = Exception.class)
    public Object updateUse(Long userId) {
        userService.updateUse(userId);
        return "";
    }


    /**
     * 根据用户编号获取授权角色
     */

    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUserServiceImpl.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */


    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */

    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    @RequestMapping(value = "/getList")
    public Object userManagementGetList(Page pageExt, @RequestParam Map<String, Object> param) {
        userService.getList(pageExt, param);
        return success(pageExt);
    }

    @RequestMapping(value = "/doDelete")
    public Object userManagementDoDelete(Long id) {
        userService.doDelete(id);
        return success();
    }

    @RequestMapping(value = "/doEdit")
    public Object userManagementDoEdit(@RequestBody SysUser user) {
        Assert.isFalse(!userService.checkPhoneUnique(user), "手机号码已存在");
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (user.getUserId() == null) {
            user.setCreateBy(getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            return toAjax(userService.insertUser(user));
        } else {
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            user.setUpdateBy(getUsername());
            return toAjax(userService.updateUser(user,false));
        }
    }

    @RequestMapping(value = "/doResetPwd")
    public Object userManagementResetPwd(SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/logout")
    public Object logout() {
        return "";

    }

    /**
     * 菜单管理 - 角色
     */
    @RequestMapping(value = "/getRoleTree")
    public Object getRoleTree() {
        return success(roleService.getRoleTree());
    }

    @RequestMapping(value = "/search/getList")
    public Object searchGetList() {
        return success(new ArrayList<Map<Object, Object>>() {
            {
                add(MapUtil.builder().put("url", "https://www.baidu.com").put("value", "百度2").build());
            }
        });
    }

    @RequestMapping(value = "/notice/getList")
    public Object noticeGetList() {
        return success(new ArrayList<Map<Object, Object>>() {
            {
                add(MapUtil.builder().put("email", "https://www.baidu.com").put("image", null).put("notice", "").build());
            }
        });
    }

    @RequestMapping(value = "/updateLoginUser")
    public Object updateLoginUser(@RequestBody SysUser user) {
        userService.updateLoginUser(user);
        return "";
    }

    @RequestMapping(value = "/setBuildWeixin")
    public Object setBuildWeixin(Integer days) {
        userService.setBuildWeixin(days);
        return "";
    }
}
